
const fsPromises = require('fs').promises;
const { LANG_CODE_REG } = require('./consts');
const { getDataByStr } = require('./addFromTsv.js');

// 这个可能需要读取一个文件夹的数据；
const default_langs = ["zh_CN","en_US","zh_HK","vi_VN","tr_TR","ru_RU","pt_PT","nl_NL","ko_KR","ja_JP","it_IT","fr_FR","es_ES","de_DE"]; //eslint-disable-line
function findLangkv(data, findKey) {
  return data.find((item) => {
    return item.key === findKey;
  });
}
function generateTsvByData(langData, langKeys) {
  let result = 'key\t' + langKeys.join('\t') + '\n';

  langData['zh_CN'].forEach((item) => {
    const { key } = item;
    result += key;
    for (let lang of langKeys) {
      let data = langData[lang] ? langData[lang] : langData['en_US'];
      const item = findLangkv(data, key);
      result += `\t${item ? item.value : ''}`;
    }
    result += '\n';
  });
  return result;
}

async function json2tsv(commandArgs) {
  const directory = commandArgs[0];
  console.log(`当前工作目录：${process.cwd()}`);
  let files = await fsPromises.readdir(`./source/${directory}`);
  const languages = [];
  files = files.filter((name) => {
    const matches = name.match(LANG_CODE_REG);
    if (matches) {
      languages.push(matches[0].replace('-', '_'));
      return true;
    }
    return false;
  });
  // 按照默认的语言顺序排序
  languages.sort((a, b) => {
    let val1 = default_langs.indexOf(a);
    let val2 = default_langs.indexOf(b);
    val1 = val1 < 0 ? val1 = 100 : val1;
    val2 = val2 < 0 ? val2 = 100 : val2;
    return val1 - val2;
  });
  // 读取files的数据
  const langData = {};
  for (const filename of files) {
    const filestr = await fsPromises.readFile(`./source/${directory}/${filename}`, { encoding: 'utf8' });
    const fileData = getDataByStr(filestr);
    const lang = filename.match(LANG_CODE_REG)[0].replace('-', '_');
    langData[lang] = fileData;
  }
  // 写tsv文件
  const name = directory.split('/').filter((name) => name.match(/\w+/)).join('/');
  await fsPromises.writeFile(`output/${name}/translation.tsv`, generateTsvByData(langData, languages));
}

module.exports.default = json2tsv;
